package com.zr.service.sys.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zr.dao.sys.SysUserDao;
import com.zr.dao.sys.SysUserRoleDao;
import com.zr.service.sys.SysUserService;
import com.zr.utils.Md5Util;
import com.zr.utils.RedisUtil;
import com.zr.utils.TokenUtil;
import com.zr.vo.sys.SysRole;
import com.zr.vo.sys.SysUser;
import com.zr.vo.sys.SysUserRole;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 用户操作 服务层实现类
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Resource
    private TokenUtil tokenUtil;

    @Resource
    private RedisUtil redisUtil;

    @Value("${img.path}")
    private  String imgPath;

    @Resource
    private SysUserDao sysUserDao;

    @Resource
    private SysUserRoleDao sysUserRoleDao;

    /**
     * 用户登录
     * @param sysUser
     * @return
     * @author liutienan
     */
    @Override
    public SysUser login(SysUser sysUser) {
        sysUser.setPassword(Md5Util.md5(sysUser.getPassword()));
        return sysUserDao.login(sysUser);
    }

    /**
     * 获取用户头像Base64编码
     * @param imgUrl
     * @return
     */
    @Override
    public String getHeadImgUrl(String imgUrl) {
        if(!StringUtils.hasLength(imgUrl)) return "";
        File file = new File(imgPath + imgUrl);
        if(file.exists()){
            return getImgBase(imgPath + imgUrl);
        }
        return "";
    }

    /**
     * 保存用户图像
     * @param file
     * @return file的base64编码
     */
    @Override
    public String setHeadImg(MultipartFile file) throws IOException {
        if(file.isEmpty()) return  "";
        String imgUrl =  UUID.randomUUID().toString() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        file.transferTo(new File(imgPath + imgUrl));
        SysUser sysUser = new SysUser();
        sysUser.setUserId(tokenUtil.currentUserId());
        sysUser.setImgUrl(imgUrl);
        sysUserDao.updateImgUrlByUserId(sysUser);
        return getImgBase(imgPath + imgUrl);
    }

    /**
     * 条件查询用户列表
     * @param sysUser
     * @return
     */
    @Override
    public PageInfo<SysUser> list(SysUser sysUser) {
        PageHelper.startPage(sysUser.getPageNum(), sysUser.getPageSize());
        List<SysUser> sysUserList = sysUserDao.list(sysUser);
        return new PageInfo<SysUser>(sysUserList);
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @Transactional
    @Override
    public int remove(Integer id) {
        SysUser sysUser = sysUserDao.selectByPrimaryKey(id);
        //删除用户角色
        sysUserRoleDao.deleteByUserId(sysUser.getUserId());
        return sysUserDao.deleteByPrimaryKey(id);
    }

    /**
     * 更改用户状态
     * @param sysUser
     * @return
     */
    @Override
    public int change(SysUser sysUser) {
        SysUser changeSysUser = new SysUser();
        changeSysUser.setId(sysUser.getId());
        changeSysUser.setStatus(sysUser.getStatus());
        changeSysUser.setModifyId(tokenUtil.currentUserId());
        changeSysUser.setModifyTime(new Date());
        return sysUserDao.updateByPrimaryKeySelective(changeSysUser);
    }

    /**
     * 新增用户
     * @param sysUser
     * @return
     */
    @Transactional
    @Override
    public int add(SysUser sysUser) {
        sysUser.setCreateId(tokenUtil.currentUserId());
        sysUser.setCreateTime(new Date());
        sysUser.setPassword(Md5Util.md5(sysUser.getPassword()));
        //新增用户角色
        insertSysRoleList(sysUser);
        return sysUserDao.insertSelective(sysUser);
    }

    /**
     * 编辑用户
     * @param sysUser
     * @return
     */
    @Transactional
    @Override
    public int edit(SysUser sysUser) {
        if(StringUtils.hasLength(sysUser.getPassword())){
            sysUser.setPassword(Md5Util.md5(sysUser.getPassword()));
        }else {
            sysUser.setPassword(null);
        }
        sysUser.setModifyId(tokenUtil.currentUserId());
        sysUser.setModifyTime(new Date());
        //删除用户角色
        sysUserRoleDao.deleteByUserId(sysUser.getUserId());
        //新增用户角色
        insertSysRoleList(sysUser);
        return sysUserDao.updateByPrimaryKeySelective(sysUser);
    }

    /**
     * 用户退出
     */
    @Override
    public void logout() {
        redisUtil.remove(tokenUtil.token());
    }


    /**
     * 将图片转换成Base64编码
     * @param imgFile 待处理图片地址
     * @return
     */
    public static String getImgBase(String imgFile) {
        // 将图片文件转化为二进制流
        InputStream in = null;
        byte[] data = null;
        // 读取图片字节数组
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 图片头
        return Base64.getEncoder().encodeToString(data);
    }

    /**
     * 批量新增用户角色
     * @param sysUser
     */
    private void insertSysRoleList(SysUser sysUser){
        if(sysUser.getSysRoleList().size() > 0){
            for(SysRole sysRole : sysUser.getSysRoleList()){
                SysUserRole userRole = new SysUserRole();
                userRole.setUserId(sysUser.getUserId());
                userRole.setRoleId(sysRole.getId());
                sysUserRoleDao.insertSelective(userRole);
            }
        }
    }

    @Override
    public List<SysUser> getPersonInfo() {
        return sysUserDao.getPersonInfo();
    }

}
